//
//  RHBrandVidioVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/10/31.
//

#import "RHBrandVidioVC.h"
#import "RHVideoCell.h"
#import "SJVideoCellViewModel.h"
#import <SJVideoPlayer/SJVideoPlayer.h>
#import "AppDelegate.h"
#import "RHSearchView.h"
#import "RHUploadVideoVC.h"
#import "RHMyShareVideoVC.h"
#import "RHVideoUploadView.h"
#import "RHBaseWebViewController.h"

@interface RHBrandVidioVC ()<UITableViewDelegate,UITableViewDataSource,SJVideoTableViewCellDelegate,QMUITextFieldDelegate>
@property (nonatomic, strong, readonly) UITableView *tableView;

@property (nonatomic, strong, nullable) SJVideoPlayer *player;

@property (nonatomic, strong) NSMutableArray<SJVideoCellViewModel *> *models;

@property (nonatomic, strong) NSMutableArray<SJVideoCellViewModel *> *searchModels;

@property (nonatomic, strong) RHSearchView *searchView;

@property (nonatomic, assign) RequestType requestType;
//当前页数
@property (nonatomic, assign) NSInteger currentPage;
//总页数
@property (nonatomic, assign) NSInteger totalPage;
//每页多少条数据
@property (nonatomic, assign) NSInteger numOfPage;

@property (nonatomic, strong) RHVideoUploadView *uploadView;
@end

@implementation RHBrandVidioVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.currentPage = 1;
    self.numOfPage = 10;
    self.requestType = RequestTypeRefresh;
    [self setupUI];
    [self getVideoData];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(void)getVideoData
{
    NSString *url = H_getInstallVideo;
    if (self.index == 1) {
        url = H_getPromotionVideo;
    }
    if (self.index == 2) {//案例分享
        url = H_getCaseStudyVideo;
    }
    [QMUITips showLoadingInView:self.view];
    NSMutableDictionary *para = @{
                           @"pageNum":@(self.currentPage),
                           @"pageSize":@(self.numOfPage),
                           @"title":self.searchView.searchTextField.text
    }.mutableCopy;
    if (self.index == 2) {
        [para setObject:@(1) forKey:@"checkStatus"];
    }
    [BaseModel startGetWithCompletionAPIKey:url argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if (resultModel.code == 200) {
            NSArray *arr = [SJVideoModel createItemsWithIndex:request.responseJSONObject[@"rows"]];
            
            NSInteger total = [request.responseObject[@"total"] integerValue];
            self.totalPage = total%self.numOfPage? total/self.numOfPage+1 : total/self.numOfPage;
            
          
            NSMutableArray *mtbArr = [NSMutableArray array];
            for ( SJVideoModel *item in arr ) {
                [mtbArr addObject:[SJVideoCellViewModel.alloc initWithItem:item]];
            }
            //下拉刷新
            if(self.requestType == RequestTypeRefresh){
                [self.tableView endHeaderRefresh];
                self.models = mtbArr;
            }else{//上拉加载
                [self.tableView endFooterRefresh];
                [self.models addObjectsFromArray:mtbArr];
            }
            if(self.currentPage >= self.totalPage){
                [self.tableView endFooterRefreshCustomWithNoMoreData];
            }
         
           
            if(arr.count == 0){
                [self.tableView endFooterRefreshWithNoMoreData];
            }
            
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}

-(void)myShareList
{
    RHMyShareVideoVC *shareListVC = [[RHMyShareVideoVC alloc]init];
    [self.navigationController pushViewController:shareListVC animated:YES];
}


- (void)coverItemWasTapped:(SJVideoTableViewCell *)cell {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    SJVideoCellViewModel *vm = _models[indexPath.row];
    
    if ( !_player ) {
        _player = [SJVideoPlayer player];
        
    }
    
    _player.URLAsset = [[SJVideoPlayerURLAsset alloc] initWithURL:vm.url playModel:[SJPlayModel playModelWithTableView:_tableView indexPath:indexPath superviewSelector:NSSelectorFromString(@"coverImageView")]];
    _player.URLAsset.title = vm.mediaTitle.string;

  
    _player.rotationObserver.onRotatingChanged = ^(id<SJRotationManager>  _Nonnull mgr, BOOL isRotating) {
        if(isRotating  ){
            if(mgr.currentOrientation == 3){
                [AppDelegate shareAppDelegate].allowRotate = YES;
            }else{
                [AppDelegate shareAppDelegate].allowRotate = NO;
            }
            
        }
    
    };
}



-(void)setupUI{
    kWeakSelf;
    //配置
    SJVideoPlayer.updateResources(^(id<SJVideoPlayerControlLayerResources>  _Nonnull resources) {
        resources.placeholder = [UIImage imageNamed:@"placeholder"];
        resources.progressThumbSize = 8;
        resources.progressTrackColor = [UIColor colorWithWhite:0.8 alpha:1];
        resources.progressBufferColor = [UIColor whiteColor];
        resources.progressThumbImage = [UIImage imageNamed:@"thumb"];
        
    });
    
    _searchView = [[RHSearchView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 55)];
    [self.view addSubview:_searchView];
    _searchView.delegate = self;
    
    UIView *tableTopView = _searchView;
    //案例分享
    if(self.index == 2 && ([PrivateMange share].currentUser.orgType == OrganizationTypeUser)){
        self.uploadView = [[RHVideoUploadView alloc]init];
        [self.view addSubview:self.uploadView];
        [self.uploadView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_offset(0);
            make.top.equalTo(weakSelf.searchView.mas_bottom);
            make.height.offset(0);
        }];
        tableTopView = self.uploadView;
        self.uploadView.hidden = YES;
    }
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView registerClass:[RHVideoCell class] forCellReuseIdentifier:@"RHVideoCell"];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    _tableView.tableFooterView = [UIView new];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [SJVideoTableViewCell registerWithTableView:_tableView];
    [self.view addSubview:_tableView];
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(tableTopView.mas_bottom);
        make.bottom.mas_offset(0);
    }];
    

    [_tableView addHeaderRefresh:^{
       
        [weakSelf.tableView.mj_footer resetNoMoreData];
        weakSelf.requestType = RequestTypeRefresh;
        weakSelf.currentPage = 1;
        [weakSelf getVideoData];
        
        
    }];
   
    [_tableView addBackFooterRefresh:^{
        weakSelf.requestType = RequestTypeAdd;
        weakSelf.currentPage++;
        [weakSelf getVideoData];
    }];
    
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    
    //案例分享
    if (self.index == 2 && ([PrivateMange share].currentUser.orgType == OrganizationTypeUser)) {
        //注册文件上传通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(videoBeginUpload:) name:VIDEO_BEGIN_UPLOAD_NOTIFICATION object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(videoUploadAction:) name:VIDEO_UPLOADING_NOTIFICATION object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(videoUploadFinish:) name:VIDEO_UPLOAD_FINISH_NOTIFICATION object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(videoDidDelete) name:VIDEO_DELETE_NOTIFICATION object:nil];
        UIBarButtonItem *list = [UIBarButtonItem itemWithImage:@"case_share" ImageHighLight:@"case_share" Target:self Seletor:@selector(myShareList) CGRect:CGRectMake(0, 0, 35, 35)];
        self.navigationItem.rightBarButtonItem = list;
        
        QMUIButton *uploadBtn = [[QMUIButton alloc]init];
        [uploadBtn setImage:[UIImage imageNamed:@"server_add_video"] forState:UIControlStateNormal];
        [uploadBtn setCornerRadius:QMUIButtonCornerRadiusAdjustsBounds];
        uploadBtn.contentMode = UIViewContentModeCenter;
        [self.view addSubview:uploadBtn];
        [uploadBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_offset(-15);
            make.bottom.mas_offset(-35-kSafe_bottom);
            make.width.height.offset(70);
        }];
        [[uploadBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf addPicAction];
//            [weakSelf.navigationController pushViewController:[RHUploadVideoVC new] animated:YES];
        }];
        
//        uploadBtn.hidden = YES;
        
    }
    
   
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.tableView.mj_footer resetNoMoreData];
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
    [self getVideoData];
    [self.searchView.searchTextField resignFirstResponder];
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    [self.tableView.mj_footer resetNoMoreData];
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getVideoData];
        [self.searchView.searchTextField resignFirstResponder];
    });
    return YES;
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return  _models.count;
}

//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//
//    return [_models[indexPath.row] height] ;
//}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return [UIView new];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SJVideoTableViewCell *cell = [SJVideoTableViewCell cellWithTableView:tableView indexPath:indexPath];
    cell.dataSource = _models[indexPath.row];
    kWeakSelf;
    SJVideoCellViewModel *model = _models[indexPath.row];
    cell.viewPdfBlock = ^{
        [weakSelf viewPdf:model.fileLink];
    };
    return cell;
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(SJVideoTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    cell.dataSource = _models[indexPath.row];
    cell.delegate = self;
}




- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.player vc_viewDidAppear];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.player vc_viewWillDisappear];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.player vc_viewDidDisappear];
}

- (BOOL)shouldAutorotate {
    return NO;
}

- (BOOL)prefersHomeIndicatorAutoHidden {
    return YES;
}

#pragma mark ----- 文件上传提示
-(void)videoBeginUpload:(NSNotification*)no
{
    UIImage *coverImage = [no object];
    self.uploadView.coverImg.image = coverImage;
    self.uploadView.hidden = NO;
    self.uploadView.progress = 0;
    [self.uploadView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.offset(40);
    }];
}

-(void)videoUploadAction:(NSNotification*)no
{
    self.uploadView.progress = [[no object] floatValue];
}

-(void)videoUploadFinish:(NSNotification*)no
{
    self.uploadView.hidden = YES;
    [self.uploadView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.offset(0);
    }];
    [self showSuccessTipView];
}

-(void)videoDidDelete
{
    [self getVideoData];
}

-(void)goToUploadVC:(NSURL*)videoUrl coverImage:(UIImage*)coverImage
{
    RHUploadVideoVC *uploadVC = [[RHUploadVideoVC alloc]initWithVideoUrl:videoUrl coverImage:coverImage];
    [self.navigationController pushViewController:uploadVC animated:YES];
    
}

-(void)showSuccessTipView
{
    kWeakSelf;
    QMUILabel *tipLab = [QMUILabel labelWithFont:kSYSTEMFONT(14) textColor:UIColor.whiteColor textAligment:NSTextAlignmentCenter];
    tipLab.text = @"分享成功！审核通过即可查看".rh_localized;
    tipLab.contentEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    tipLab.backgroundColor = kCOLOR_HEX_A(@"000000", 0.7);
    tipLab.layer.cornerRadius = 5;
    tipLab.numberOfLines = 0;
    tipLab.layer.masksToBounds = YES;
    [self.view addSubview:tipLab];
    [tipLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.searchView.mas_bottom);
        make.centerX.mas_offset(0);
        make.width.lessThanOrEqualTo(@(kUI_WINDOW_W));
       
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [tipLab removeFromSuperview];
    });
}

#pragma mark ----- 查看PDF
-(void)viewPdf:(NSString*)pdfLink
{
    RHBaseWebViewController *pdfVC = [[RHBaseWebViewController alloc]init];
    pdfVC.urlStr = pdfLink;
    pdfVC.navTitle = pdfLink.lastPathComponent;
    [self.navigationController pushViewController:pdfVC animated:YES];
}

#pragma mark - Action
- (void)addPicAction{
    
    [self norSheetViewWithTitle:@""
                        mess:@""
                            theme:UIColor.blackColor
                            oneTitle:@"相机".rh_localized
                               twoTitle:@"相册".rh_localized
                                       oneHandler:^{
        [self addPhotoFromCamera];
    }
                                       twoHandler:^{
        [self addPhotoFromAlbum:NO];
        
   }];
}


//从相机拍照
- (void)addPhotoFromCamera{
    if (![ZLPhotoManager haveCameraAuthority]) {
        NSString *message = [NSString stringWithFormat:GetLocalLanguageTextValue(ZLPhotoBrowserNoCameraAuthorityText), kAPPName];
        [SVProgressHUD showInfoWithStatus:message];
        return;
    }
    
    ZLCustomCamera *camera = [[ZLCustomCamera alloc] init];
    camera.allowTakePhoto = NO;
    camera.allowRecordVideo = YES;
    camera.sessionPreset = ZLCaptureSessionPreset640x480;
    //最大录制时长
    camera.maxRecordDuration = 300;
    kWeakSelf;
    camera.doneBlock = ^(UIImage *image, NSURL *videoUrl) {
        
        UIImage *coverimage = [weakSelf xy_getVideoThumbnail:videoUrl];
        [weakSelf goToUploadVC:videoUrl coverImage:coverimage];
    };
    [self showDetailViewController:camera sender:nil];
}

//从相册选择图片
//hasCamera -- 是否附带拍照
- (void)addPhotoFromAlbum:(BOOL)hasCamera{
    ZLPhotoActionSheet *actionSheet = [[ZLPhotoActionSheet alloc] init];
    //设置语言
    actionSheet.configuration.languageType = (ZLLanguageType)[[kUserDefaults objectForKey:@"ZLLanguage"]integerValue];
    //是否升序排列，预览界面不受该参数影响
    actionSheet.configuration.sortAscending = NO;
    //设置相册内部显示拍照按钮
    actionSheet.configuration.allowTakePhotoInLibrary = hasCamera?YES:NO;
    
    actionSheet.configuration.maxSelectCount = 1;
    
    //设置在内部拍照按钮上实时显示相机俘获画面
    actionSheet.configuration.showCaptureImageOnTakePhotoBtn = hasCamera?YES:NO;
    //设置是否允许选择原图
    actionSheet.configuration.allowSelectOriginal = YES;
    //设置是否允许选择视频
    actionSheet.configuration.allowSelectVideo = YES;
    //最大录制时长
    actionSheet.configuration.maxRecordDuration = 300;
    //允许选择视频的最大时长
    actionSheet.configuration.maxVideoDuration = 300;
    //设置是否允许选择图片
    actionSheet.configuration.allowSelectImage = NO;
    //设置是否允许选择gif
    actionSheet.configuration.allowSelectGif = NO;
    //是否显示选中图片的index 默认YES
    actionSheet.configuration.showSelectedIndex = NO;
    //是否允许编辑图片
    actionSheet.configuration.allowEditImage = NO;
    //是否允许编辑视频
    actionSheet.configuration.allowEditVideo = NO;
    //预览选择模式下 拍照/相册/取消 的字体颜色 默认 blackColor
    actionSheet.configuration.previewTextColor = kCOLOR_HEX(@"#666666");
    //遮罩层颜色， 默认 blackColor alpha 0.2
    actionSheet.configuration.selectedMaskColor = [[UIColor blackColor] colorWithAlphaComponent: 0.7f];
    // 导航条颜色，默认 rgb(44, 45, 46)
    actionSheet.configuration.navBarColor = [UIColor whiteColor];
    // 导航标题颜色，默认 white
    actionSheet.configuration.navTitleColor = kCOLOR_HEX(@"#222222");
    // 底部工具栏按钮 可交互 状态标题颜色，默认 white
    actionSheet.configuration.bottomBtnsNormalTitleColor = kCOLOR_HEX(@"#222222");
    //底部工具栏按钮 可交互 状态背景颜色，默认rgb(80, 169, 56)
    actionSheet.configuration.bottomBtnsNormalBgColor = kCOLOR_HEX(@"#e9e9e9");
    //底部工具栏按钮 不可交互 状态背景颜色，默认rgb(39, 80, 32)
    //actionSheet.configuration.bottomBtnsDisableBgColor = CDisBtnColor;
    // 底部工具条底色，默认 rgb(44, 45, 46)
    actionSheet.configuration.bottomViewBgColor = kCOLOR_HEX(@"#ffffff");
    //设置照片 cell的圆角弧度
    actionSheet.configuration.cellCornerRadio = 5.0;
    //状态栏样式 默认 UIStatusBarStyleLightContent
    actionSheet.configuration.statusBarStyle = UIStatusBarStyleDefault;
    //设置照片最大预览数
    //actionSheet.configuration.maxPreviewCount = 2;
    //设置照片最大选择数
    actionSheet.configuration.maxSelectCount = 1;
    
    actionSheet.sender = self;

    [actionSheet showPhotoLibrary];
   
    kWeakSelf;
    [actionSheet setSelectImageBlock:^(NSArray<UIImage *> * _Nonnull images, NSArray<PHAsset *> * _Nonnull assets, BOOL isOriginal) {
        
        PHAssetResource *resource = [[PHAssetResource assetResourcesForAsset:[assets firstObject]] firstObject];
        long long size = [[resource valueForKey:@"fileSize"] longLongValue];
        
        NSLog(@"------>视频大小:%lld KB",size/1024);
        if (size > 500*(1024*1024)) {
            [QMUITips showInfo:[NSString stringWithFormat:@"视频大小不能超过%@".rh_localized,@"500M"]];
            return;
        }
        
        [QMUITips showLoadingInView:[UIApplication sharedApplication].keyWindow];
        [[PHImageManager defaultManager] requestExportSessionForVideo:[assets firstObject] options:nil exportPreset:AVAssetExportPreset640x480  resultHandler:^(AVAssetExportSession * _Nullable exportSession, NSDictionary * _Nullable info) {
           
//            NSLog(@"------->视频信息:%@",info);
            AVURLAsset *urlAsset = (AVURLAsset*)exportSession.asset;

            NSURL *url = urlAsset.URL;
            NSData *videoData = [NSData dataWithContentsOfURL:url];
            NSLog(@"------>导出后的视频大小:%ld KB",videoData.length/1024);
            //
            UIImage *coverImage = [weakSelf xy_getVideoThumbnail:url];
            dispatch_async(dispatch_get_main_queue(), ^{
                [QMUITips hideAllTipsInView:[UIApplication sharedApplication].keyWindow];
                [weakSelf goToUploadVC:url coverImage:coverImage];
                NSLog(@"------------>%@",url);
            });
            

//            NSData  *data = [NSData dataWithContentsOfURL:urlAsset.URL];

            
        }];

    }];

    actionSheet.selectImageRequestErrorBlock = ^(NSArray<PHAsset *> * _Nonnull errorAssets, NSArray<NSNumber *> * _Nonnull errorIndex) {
        
    };
    
    actionSheet.cancleBlock = ^{
        
       
    };
}

//MARK: NOTE == 普通Sheet弹窗，按钮1和按钮2  主题色
- (void)norSheetViewWithTitle:(NSString *)title
                         mess:(NSString *)mess
                        theme:(UIColor *)themeColor
                     oneTitle:(NSString *)oneTitle
                     twoTitle:(NSString *)twoTitle
                   oneHandler:(dispatch_block_t)oneHandler
                   twoHandler:(dispatch_block_t)twoHandler{
    // 底部按钮
    QMUIAlertAction *action1 = [QMUIAlertAction actionWithTitle: @"取消".rh_localized style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        
    }];
    QMUIAlertAction *action2 = [QMUIAlertAction actionWithTitle: oneTitle style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if (oneHandler) {
            oneHandler();
        }
    }];

    QMUIAlertAction *action3 = [QMUIAlertAction actionWithTitle: twoTitle style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        if (twoHandler) {
            twoHandler();
        }
    }];
    
    QMUIAlertController *alertController = [[QMUIAlertController alloc] initWithTitle: title message: mess preferredStyle:QMUIAlertControllerStyleActionSheet];
    /// sheet内容的圆角，默认值是 13，以保持与系统默认样式一致
    alertController.sheetContentCornerRadius = 6;
    /// sheet按钮高度，默认值是 57，以保持与系统默认样式一致
    alertController.sheetButtonHeight = 58;
    alertController.sheetContentMargin = UIEdgeInsetsMake(10, 12, 10, 12);
    /// sheet的最大宽度，默认值是5.5英寸的屏幕的宽度减去水平的 sheetContentMargin
    //alertController.sheetContentMaximumWidth = 320;
    
    NSMutableDictionary *titleAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetTitleAttributes];
    titleAttributs[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#222222");
    titleAttributs[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    titleAttributs[NSParagraphStyleAttributeName] = [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight: 22 lineBreakMode: NSLineBreakByTruncatingTail textAlignment: NSTextAlignmentCenter];
    
    /// sheet标题样式，默认@{NSForegroundColorAttributeName:UIColorMake(143, 143, 143),NSFontAttributeName:UIFontBoldMake(13),NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:0 lineBreakMode:NSLineBreakByTruncatingTail]}
    alertController.sheetTitleAttributes = titleAttributs;
    
    NSMutableDictionary *messageAttributs = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetMessageAttributes];
     messageAttributs[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#444444");
       messageAttributs[NSFontAttributeName] = [UIFont systemFontOfSize:14];
       messageAttributs[NSParagraphStyleAttributeName] = [NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight: 22 lineBreakMode: NSLineBreakByTruncatingTail];
    /// sheet信息样式，默认@{NSForegroundColorAttributeName:UIColorMake(143, 143, 143),NSFontAttributeName:UIFontMake(13),NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:0 lineBreakMode:NSLineBreakByTruncatingTail]}
    alertController.sheetMessageAttributes = messageAttributs;
    
    //alert头部（非按钮部分）背景色
    alertController.alertHeaderBackgroundColor = UIColorWhite;
    //alert按钮背景色
    alertController.alertButtonBackgroundColor = UIColorWhite;
    //alert上分隔线颜色
    alertController.alertSeparatorColor = kCOLOR_HEX(@"#f5f5f5");
    /// alert头部title和message之间的间距
    alertController.alertTitleMessageSpacing = 5;
    
    NSMutableDictionary *buttonAttributes = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetButtonAttributes];
    buttonAttributes[NSForegroundColorAttributeName] = kCOLOR_HEX(@"#666666");
    buttonAttributes[NSFontAttributeName] = [UIFont systemFontOfSize:16];

    alertController.sheetButtonAttributes = buttonAttributes;
    
    NSMutableDictionary *cancelButtonAttributes = [[NSMutableDictionary alloc] initWithDictionary:alertController.sheetCancelButtonAttributes];
    cancelButtonAttributes[NSForegroundColorAttributeName] = themeColor;
    cancelButtonAttributes[NSFontAttributeName] = [UIFont systemFontOfSize:16];
    alertController.sheetCancelButtonAttributes = cancelButtonAttributes;
    
    [alertController addAction:action1];
    [alertController addAction:action2];
    [alertController addAction:action3];
    [alertController showWithAnimated:YES];
}

#pragma mark -------- 获取视频第一帧做封面
- (UIImage *)xy_getVideoThumbnail:(NSURL *)filePath
{
//    NSURL *sourceURL = [NSURL fileURLWithPath:filePath];
    AVAsset *asset = [AVAsset assetWithURL:filePath];
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc]initWithAsset:asset];
    imageGenerator.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMake(0, 1);
    NSError *error;
    CGImageRef imageRef = [imageGenerator copyCGImageAtTime:time actualTime:NULL error:&error];
    UIImage *thumbnail = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);  // CGImageRef won't be released by ARC
    return thumbnail;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
